package com.cxlin.cwanandroid.ui.blog

import android.os.Bundle
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.cxlin.base.BaseFragment
import com.cxlin.base.ext.binding
import com.cxlin.base.ext.newInstanceFragment
import com.cxlin.base.ext.toast
import com.cxlin.base.mvi.ext.collectFLow
import com.cxlin.cwanandroid.R
import com.cxlin.cwanandroid.databinding.FragmentTabBlogBinding
import com.cxlin.cwanandroid.model.bean.SystemParent
import com.cxlin.cwanandroid.ui.blog.viewmodel.TabBlogViewModel
import com.cxlin.cwanandroid.ui.login.viewmodel.LoginViewModel
import com.google.android.material.tabs.TabLayoutMediator
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 *
 * @Author: chenxunlin
 * @Date: 2024/4/25 16:40
 */
class BlogTabFragment : BaseFragment() {

    private val binding by binding<FragmentTabBlogBinding>()
    private val viewModel by viewModel<TabBlogViewModel>()

    override fun getLayoutId() = R.layout.fragment_tab_blog

    private val mBlogTypes = mutableListOf<SystemParent>()

    override fun initView() {
        binding.viewPager.offscreenPageLimit = 1
        binding.viewPager.adapter = object : FragmentStateAdapter(this){
            override fun getItemCount(): Int = mBlogTypes.size

            override fun createFragment(position: Int) : Fragment {
                return  requireActivity().newInstanceFragment<BlogFragment>(
                    Bundle().apply {
                        putSerializable("cid",mBlogTypes[position].id) }
                )
            }

        }

        TabLayoutMediator(binding.tabLayout,binding.viewPager){tab,position->
            tab.text = mBlogTypes[position].name
        }.attach()
    }

    override fun initData() {
        viewModel.sendIntent(TabBlogViewModel.TabBLogUiIntent.GetBlogType())
    }

    override fun observeStateAndEvent(){
        viewModel.uiStateFlow.collectFLow(this){
            when(this){
                is TabBlogViewModel.TabBlogUiState.BlogTypes -> {
                    this.result?.let {
                        mBlogTypes.clear()
                        mBlogTypes.addAll(it)
                        binding.viewPager.adapter?.notifyDataSetChanged()
                    }
                }
                else -> {}
            }
        }

        viewModel.effectFlow.collectFLow(this){
            when(this){
                is LoginViewModel.LoginEvent.ToastEvent -> {
                    requireActivity().toast(
                        this.message,
                        if (this.short) Toast.LENGTH_SHORT else Toast.LENGTH_LONG
                    )
                }
            }
        }
    }
}